﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using Agile.Engine.Data;

namespace Fis.Win.Utils
{
    public class CacheContext
    {
        readonly static Dictionary<string, DataTable> registry = new Dictionary<string, DataTable>();
        readonly static DataContext dataContext = DataContext.Get("CacheDataContext");
        readonly static object syncRoot = new object();

        public static void RefresheConfig()
        {
            ///会计制度
            registry["ACCKIND"] = UIUtils.ViewConfig.Tables["acckind"];
            ///辅助核算
            registry["AIDSGROUP"] = UIUtils.ViewConfig.Tables["AIDSGROUP"];
            ///凭证类型大类
            registry["BILLTYPEKIND"] = UIUtils.ViewConfig.Tables["BILLTYPEKIND"];

            if (AppSession.Book != null)
            {
                ///凭证类型
                registry["BILLTYPE"] = UIUtils.ViewConfig.Tables["BILLTYPE"].Select(string.Format("kind='{0}'", AppSession.Book["FBILLTYPE"])).CopyToDataTable();
                ///科目类型
                registry["ACCSYSTEM"] = UIUtils.ViewConfig.Tables["accdata"].Select(String.Format("kind='{0}'", AppSession.Book["FACCSYSTEM"])).CopyToDataTable();
            }
        }

        public static ICollection<string> CacheKeys
        {
            get
            {
                return registry.Keys;
            }
        }

        public static string DefaultCurrencyRate
        {
            get { return "defaultCurrencyRate"; }
        }

        public static DataTable GetCache(string tableName)
        {
            lock (syncRoot)
            {
                if (!registry.ContainsKey(tableName.ToUpper()))
                    RefreshCache(tableName.ToUpper());
                return registry[tableName.ToUpper()];
            }
        }

        public static DataTable LowerAccountCache()
        {
            var d = GetCache("TACCOUNT");
            var rate = GetCache("TRATE");
            rate.PrimaryKey = new DataColumn[] { rate.Columns["SID"] };
            var f = from r in d.Select("FPARENT is not null")
                    select r["FPARENT"].ToString();
            var filter = string.Format("SID NOT IN ('{0}')", string.Join("','", f.ToArray()));

            var l = d.Select(filter, "FCODE").CopyToDataTable();

            l.Columns.Add("FRATECODE");
            l.Columns.Add("FRATENAME");

            foreach (var i in l.AsEnumerable())
            {
                i["FRATECODE"] = rate.Rows.Find(i["FBZ"])["FCODE"];
                i["FRATENAME"] = rate.Rows.Find(i["FBZ"])["FNAME"];
            }

            return l;
        }

        public static void ClearCache()
        {
            lock (syncRoot)
            {
                registry.Clear();
            }
        }

        public static void RefreshCache(string tableName)
        {
            lock (syncRoot)
            {
                registry[tableName.ToUpper()] = null;
                DataAccess a = new DataAccess() { Context = dataContext, TableName = tableName };

                switch (tableName.ToUpper())
                {
                    case "ACCKIND":
                    case "AIDSGROUP":
                    case "BILLTYPE":
                    case "ACCSYSTEM":
                    case "BILLTYPEKIND":
                        RefresheConfig();
                        break;
                    case "TRIGHTS":
                        registry["TRIGHTS"] = a.Query(string.Format("FUSERID='{0}'", AppSession.UserSID));
                        break;
                    default:
                        registry[tableName.ToUpper()] = a.GetData();
                        break;
                }
            }
        }

        public static DataTable YesNoCache()
        {
            var yesno = new object[]{
                new object[]{"0", "否"},
                new object[]{"1", "是"}
            };
            return KeyValueData(yesno);
        }

        public static DataTable DebitCreditCache()
        {
            var yesno = new object[]{
                new object[]{"0", "平"},
                new object[]{"1", "借"},
                new object[]{"2", "贷"}
            };
            return KeyValueData(yesno);
        }

        public static DataTable WBHSCache()
        {
            var yesno = new object[]{
                new object[]{"0", "不核算"},
                new object[]{"1", "日结"},
                new object[]{"2", "月结"}
            };
            return KeyValueData(yesno);

        }

        public static DataTable RightsCache()
        {
            var yesno = new object[]{
                new object[]{0, "操作员"},
                new object[]{1, "主管"}
            };
            return KeyValueData(yesno);
        }

        public static DataTable StateCache()
        {
            var yesno = new object[]{
                new object[]{-1,"冻结"},
                new object[]{0, "启用"}
            };
            return KeyValueData(yesno);
        }

        public static DataTable BillStatusCache()
        {
            //0.初始；1.已审核；2.已记账
            var status = new object[]{
                new object[]{0, "初始录入"}
                ,new object[]{1, "已审核"}
                ,new object[]{2, "已记账"}
                ,new object[]{4, "期初凭证"}
            };
            return KeyValueData(status);
        }

        private static DataTable KeyValueData(params object[] args)
        {
            var d = new DataTable();
            d.Columns.Add("value");
            d.Columns.Add("display");

            foreach (var i in args)
                d.Rows.Add(i as object[]);
            return d;
        }

    }
}
